package com.hjs.pacloudservice.util;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @auther hanjinsong
 * @create 2019-08-05 20:18
 */


@Component
@Slf4j
public class RedisUtils {

    private Logger logger = LoggerFactory.getLogger(RedisUtils.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public String get(final String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 取出所有的value
     */
    public List<String> getAllValues(){
        Set<String> keys = redisTemplate.keys("*");
        List<String> list = new ArrayList<>();
        for(String key : keys){
            String value = redisTemplate.opsForValue().get(key);
            list.add(value);
        }
        return list;
    }


    /**
     * 取出所有的key和value
     * @return
     */
    public HashMap getRedis(){
        Set<String> keys = redisTemplate.keys("*");
        HashMap<Object, Object> hashMap = new HashMap<>();
        for(String key : keys){
            Object value = redisTemplate.opsForValue().get(key);
            hashMap.put(key,value);
        }
        return hashMap;
    }

    /**
     * 写入缓存
     */
    public boolean set(final String key, String value) {
        boolean result = false;
        try {
            logger.info("开始写入redis：set key:{} value:{}",key, value);
            redisTemplate.opsForValue().set(key, value);
            logger.info("写入成功redis：set key:{} value:{}",key, value);
            result = true;
        } catch (Exception e) {
            logger.error("set key:{} value:{} error",key,value,e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 更新缓存
     */
    public boolean getAndSet(final String key, String value) {
        boolean result = false;
        try {
            logger.info("更新写入redis：set key:{} value:{}",key, value);
            redisTemplate.opsForValue().getAndSet(key, value);
            logger.info("更新成功redis：set key:{} value:{}",key, value);
            result = true;
        } catch (Exception e) {
            logger.info("redis：set key:{} value:{}error",key, value,e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除缓存
     */
    public boolean delete(final String key) {
        boolean result = false;
        try {
            logger.info("删除key:{}的缓存",key);
            redisTemplate.delete(key);
            logger.info("成功删除key:{}的缓存",key);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }
}
